package com.ng.biz.controller;

import java.util.Date;
import java.util.List;

import org.springframework.web.bind.annotation.*;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.ng.biz.model.domain.BlueprintNode;
import com.ng.biz.model.domain.BlueprintNodeCategory;
import com.ng.common.annotation.TokenRequired;
import com.ng.common.annotation.Tx;
import com.ng.common.controller.Controller;
import com.ng.common.model.response.R;
import com.ng.common.util.UuidUtil;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor;

@Tag(name = "蓝图节点管理")
@RequiredArgsConstructor
@RestController
@RequestMapping("/biz/blueprint/node")
public class BlueprintNodeController extends Controller {
	
	  @Operation(summary = "获取蓝图节点类别列表")
	    @Parameters({
	        @Parameter(name = "keywords", description = "关键字", required = false),
	        @Parameter(name = "cur", description = "当前页码", required = true),
	        @Parameter(name = "limit", description = "每页数据量", required = true)
	    })
	    @TokenRequired
	    @GetMapping("/category/pages")
	    public R<List<BlueprintNodeCategory>> pagesCategory(
	            HttpServletRequest request,
	            @RequestParam(name = "keywords", required = false, defaultValue = "") String keywords,
	            @RequestParam(name = "cur", required = false, defaultValue = "1") int cur,
	            @RequestParam(name = "limit", required = false, defaultValue = "10") int limit) {
	        
	        String sqlExceptSelect = " from " + BlueprintNodeCategory.TABLE_NAME + " a WHERE 1=1 ";
	        if (!StrKit.isBlank(keywords)) {
	            sqlExceptSelect += " and a.name like '%" + keywords + "%' ";
	        }
	        sqlExceptSelect += " ORDER BY a.sort asc ";
	        List<BlueprintNodeCategory> page = BlueprintNodeCategory.dao.find("select a.* " + sqlExceptSelect);
	        return R.ok(page);
	    }

	    @Operation(summary = "保存蓝图节点类别信息")
	    @Parameters({
	        @Parameter(name = "blueprintDesigner", description = "蓝图节点类别信息", required = true)
	    })
	    @TokenRequired
	    @Tx
	    @PostMapping("/category/save")
	    public R<BlueprintNodeCategory> saveCategory(HttpServletRequest request, @RequestBody BlueprintNodeCategory blueprintNodeCategory) {
	        try {
	            if (StrKit.notBlank(blueprintNodeCategory.getId())) {
	            	blueprintNodeCategory.setUpdateUserId(getUserId(request));
	            	blueprintNodeCategory.setUpdateTime(new Date(System.currentTimeMillis()));
	                if (blueprintNodeCategory.update()) {
	                    return R.ok(blueprintNodeCategory);
	                } else {
	                    return R.failed("更新失败！");
	                }
	            } else {
	            	blueprintNodeCategory.setId(UuidUtil.getUUID());
	            	blueprintNodeCategory.setCreateUserId(getUserId(request));
	            	blueprintNodeCategory.setCreateTime(new Date(System.currentTimeMillis()));
	                if (blueprintNodeCategory.save()) {
	                    return R.ok(blueprintNodeCategory);
	                } else {
	                    return R.failed("保存失败.");
	                }
	            }
	        } catch (Exception e) {
	            return R.failed(e.getMessage());
	        }
	    }

	    @Operation(summary = "删除蓝图节点类别信息")
	    @Parameters({
	        @Parameter(name = "ids", description = "蓝图节点类别id集合(逗号分割)", required = true)
	    })
	    @DeleteMapping("/category/{ids}")
	    @TokenRequired
	    @Tx
	    public R<String> deleteCategory(@PathVariable("ids") String ids) {
	        String[] arr = ids.split(",");
	        if (ids == null || ids.length() <= 0) {
	            return R.failed("请选择需要删除的蓝图节点类别信息.");
	        }
	        for (String id : arr) {
	        	BlueprintNodeCategory.dao.deleteById(id);
	        	Db.delete("delete from "+BlueprintNode.TABLE_NAME+" where category_id=?",id);
	        }
	        return R.ok();
	    }

    @Operation(summary = "获取蓝图节点列表")
    @Parameters({
        @Parameter(name = "keywords", description = "关键字", required = false),
        @Parameter(name = "categoryId", description = "关键字", required = false),
        @Parameter(name = "cur", description = "当前页码", required = true),
        @Parameter(name = "limit", description = "每页数据量", required = true)
    })
    @TokenRequired
    @GetMapping("/pages")
    public R<Page<BlueprintNode>> pages(
            HttpServletRequest request,
            @RequestParam(name = "keywords", required = false, defaultValue = "") String keywords,
            @RequestParam(name = "categoryId", required = false, defaultValue = "") String categoryId,
            @RequestParam(name = "cur", required = false, defaultValue = "1") int cur,
            @RequestParam(name = "limit", required = false, defaultValue = "10") int limit) {
        
        String sqlExceptSelect = " from " + BlueprintNode.TABLE_NAME + " a WHERE 1=1 ";
        if (!StrKit.isBlank(keywords)) {
            sqlExceptSelect += " and a.name like '%" + keywords + "%' ";
        }
        if (!StrKit.isBlank(categoryId)) {
            sqlExceptSelect += " and a.category_id = '" + categoryId + "' ";
        }
        sqlExceptSelect += " ORDER BY a.sort asc ";
        Page<BlueprintNode> page = BlueprintNode.dao.paginate(cur, limit, "select a.* ", sqlExceptSelect);
        return R.ok(page);
    }

    @Operation(summary = "保存蓝图节点信息")
    @Parameters({
        @Parameter(name = "blueprintDesigner", description = "蓝图节点信息", required = true)
    })
    @TokenRequired
    @Tx
    @PostMapping("/save")
    public R<BlueprintNode> save(HttpServletRequest request, @RequestBody BlueprintNode blueprintNode) {
        try {
            if (StrKit.notBlank(blueprintNode.getId())) {
            	blueprintNode.setUpdateUserId(getUserId(request));
            	blueprintNode.setUpdateTime(new Date(System.currentTimeMillis()));
                if (blueprintNode.update()) {
                    return R.ok(blueprintNode);
                } else {
                    return R.failed("更新失败！");
                }
            } else {
            	blueprintNode.setId(UuidUtil.getUUID());
            	blueprintNode.setCreateUserId(getUserId(request));
            	blueprintNode.setCreateTime(new Date(System.currentTimeMillis()));
                if (blueprintNode.save()) {
                    return R.ok(blueprintNode);
                } else {
                    return R.failed("保存失败.");
                }
            }
        } catch (Exception e) {
            return R.failed(e.getMessage());
        }
    }

    @Operation(summary = "删除蓝图节点信息")
    @Parameters({
        @Parameter(name = "ids", description = "蓝图节点id集合(逗号分割)", required = true)
    })
    @DeleteMapping("/{ids}")
    @TokenRequired
    @Tx
    public R<String> delete(@PathVariable("ids") String ids) {
        String[] arr = ids.split(",");
        if (ids == null || ids.length() <= 0) {
            return R.failed("请选择需要删除的蓝图节点信息.");
        }
        for (String id : arr) {
        	BlueprintNode.dao.deleteById(id);
        }
        return R.ok();
    }
    
    @Operation(summary = "获取蓝图类别和类别明细")
    @TokenRequired
    @GetMapping("/categories")
    public R<List<BlueprintNodeCategory>> getNodeCategories() {
    	List<BlueprintNodeCategory> nodeCategories=BlueprintNodeCategory.dao.find("select id,parent_id,name,description from "+BlueprintNodeCategory.TABLE_NAME+"  order by sort asc ");
    	for(BlueprintNodeCategory category:nodeCategories) {
    		category.setNodes(BlueprintNode.dao.find("select id,category_id as parent_id ,type,label,icon,width,show_head,color,data,description from "+BlueprintNode.TABLE_NAME+" where category_id=? ORDER BY sort asc",category.getId()));
    	}
        return R.ok(nodeCategories);
    }
}
